package bigbeard.tools.net.server;


import bigbeard.tools.net.api.DataArrivalCallback;
import bigbeard.tools.net.api.StateChangeCallback;
import bigbeard.tools.net.api.server.ClientAcceptCallback;
import bigbeard.tools.net.api.server.IConnector;
import bigbeard.tools.net.api.server.IServer;
import bigbeard.tools.thread.pools.ThreadPoolFactory;

import java.util.concurrent.ExecutorService;

/**
 * @author bigbeard on 2022-09-29
 */
public abstract class BaseServerImpl implements IServer {
    protected DataArrivalCallback dataArrivalCallback;
    protected StateChangeCallback stateChangeCallback;
    protected ClientAcceptCallback clientAcceptCallback;

    private static final String THREAD_NAME_PREFIX = "net-notify-thread-%s";

    protected ExecutorService executorService = ThreadPoolFactory.createNotifyThreadPool(THREAD_NAME_PREFIX);

    @Override
    public void onDataArrival(DataArrivalCallback callback) {
        dataArrivalCallback = callback;
    }

    @Override
    public void onStateChange(StateChangeCallback callback) {
        this.stateChangeCallback = callback;
    }

    @Override
    public void onClientAccept(ClientAcceptCallback callback) {
        this.clientAcceptCallback = callback;
    }

    protected void notifyState(String key, int state, String info) {
        if (null != stateChangeCallback) {
            executorService.execute(() -> stateChangeCallback.notifyStateChange(key, state, info));
        }
    }

    protected void notifyDataArrival(String key, byte[] data) {
        if (null != dataArrivalCallback) {
            dataArrivalCallback.callback(key, data);
        }
    }

    protected void notifyClientAccept(String key, IConnector connector) {
        if (null != clientAcceptCallback) {
            executorService.execute(() -> clientAcceptCallback.accept(key, connector));
        }
    }
}
